//
//  oldMapLocationViewController.m
//  laonianbang
//
//  Created by 勇拓 李 on 18/3/12.
//  Copyright © 2018年 zaiyou. All rights reserved.
//

#import "oldMapLocationViewController.h"
#import <BaiduMapAPI_Map/BMKMapView.h>
#import <BaiduMapAPI_Map/BMKPointAnnotation.h>
#import <BaiduMapAPI_Location/BMKLocationService.h>
#import <BaiduMapAPI_Search/BMKGeocodeSearch.h>
#import "oldEditAddressViewController.h"
#import "oldMapSearchViewController.h"

@interface oldMapLocationViewController ()<BMKMapViewDelegate, BMKGeoCodeSearchDelegate, BMKLocationServiceDelegate>
{
    BMKMapView *_mapView;//地图
    BMKLocationService *_locService;//定位
    BMKGeoCodeSearch *_geocodesearch; //地理编码主类，用来查询、返回结果信息
}
@property (weak, nonatomic) IBOutlet UILabel *label_address;
@property (weak, nonatomic) IBOutlet UIButton *btn_confirm;
@property (weak, nonatomic) IBOutlet UIView *bottom_view;
@property (weak, nonatomic) IBOutlet UIButton *btn_center;

@end

@implementation oldMapLocationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [_mapView viewWillAppear];
    
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    
    //初始化逆地理编码类
    BMKReverseGeoCodeOption *reverseGeoCodeOption= [[BMKReverseGeoCodeOption alloc] init];
    //需要逆地理编码的坐标位置
    
    if(_addressInfo.lng && _addressInfo.lat)
    {
        _mapView.centerCoordinate = CLLocationCoordinate2DMake([_addressInfo.lat floatValue], [_addressInfo.lng floatValue]);
        _label_address.text = _addressInfo.address;
    }
    else
    {
        _addressInfo = [[oldAddressInfo alloc] init];
    }
    
    reverseGeoCodeOption.reverseGeoPoint = _mapView.centerCoordinate;
    
    BOOL reg = [_geocodesearch reverseGeoCode:reverseGeoCodeOption];
    if (reg) {
        NSLog(@"_____编码成功");
    }else{
        NSLog(@"_____编码失败");
    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [_mapView viewWillDisappear];
    
    _mapView.delegate = nil; // 不用时，置nil
    
}

#pragma mark -initView
- (void)initView
{
    self.navigationItem.title = @"地址选择";
    
    _bottom_view.layer.shadowColor = [UIColor blackColor].CGColor;
    _bottom_view.layer.shadowOpacity = 0.8f;
    _bottom_view.layer.shadowOffset = CGSizeMake(1,1);
    
    UITapGestureRecognizer *tapView=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapChange:)];
    [_bottom_view addGestureRecognizer:tapView];
    
    [_btn_confirm addTarget:self action:@selector(btn_confirm_tapped:) forControlEvents:UIControlEventTouchDown];
    
    _mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    
    _mapView.showsUserLocation = YES; //是否显示定位图层（即我的位置的小圆点）
    
    _mapView.minZoomLevel = 19;//地图显示比例
    _mapView.maxZoomLevel = 21;
    
    _mapView.mapType = BMKMapTypeStandard;//设置地图为空白类型
    
    _mapView.userTrackingMode = BMKUserTrackingModeNone;
    
    [self.view addSubview:_mapView];
    
    [self.view bringSubviewToFront:_bottom_view];
    [self.view bringSubviewToFront:_btn_confirm];
    [self.view bringSubviewToFront:_btn_center];
    //
    
    _geocodesearch = [[BMKGeoCodeSearch alloc] init];
    
    _geocodesearch.delegate = self;

    [self startLocation];//开始定位方法
}

//开始定位

-(void)startLocation

{
    
    //初始化BMKLocationService
    
    _locService = [[BMKLocationService alloc]init];
    
    _locService.delegate = self;
    
    _locService.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    
    //启动LocationService
    
    [_locService startUserLocationService];
    
}

- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
    
    CLLocationCoordinate2D centerCoordinate = mapView.region.center;
    
    //初始化逆地理编码类
    BMKReverseGeoCodeOption *reverseGeoCodeOption= [[BMKReverseGeoCodeOption alloc] init];
    //需要逆地理编码的坐标位置
    reverseGeoCodeOption.reverseGeoPoint = centerCoordinate;
    BOOL reg = [_geocodesearch reverseGeoCode:reverseGeoCodeOption];
    if (reg) {
        NSLog(@"_____编码成功");
    }else{
        NSLog(@"_____编码失败");
    }
    
}

#pragma mark - 保存
- (void)btn_confirm_tapped:(id)sender
{
    _addressInfo.lat = [NSString stringWithFormat:@"%f", _mapView.region.center.latitude];
    _addressInfo.lng = [NSString stringWithFormat:@"%f", _mapView.region.center.longitude];
    
    UIViewController *vc = self.navigationController.viewControllers[[self.navigationController.viewControllers count] - 2];
    
    if ([vc isKindOfClass:[oldEditAddressViewController class]]) {
        oldEditAddressViewController *oldVc = (oldEditAddressViewController *)vc;
        oldVc.addressInfo = _addressInfo;
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)tapChange:(id)sender
{
    oldMapSearchViewController *vc = [oldMapSearchViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - delegate
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation

{
    
    NSLog(@"heading is %@",userLocation.heading);
    
}

- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation

{
    
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    if (_addressInfo.lat && _addressInfo.lng) {
        [_locService stopUserLocationService];
        return;
    }
    else
    {
        _mapView.centerCoordinate = userLocation.location.coordinate;
        _addressInfo.lat = [NSString stringWithFormat:@"%f", userLocation.location.coordinate.latitude];
        _addressInfo.lng = [NSString stringWithFormat:@"%f", userLocation.location.coordinate.longitude];
    }
    
    //普通态
    
    //以下_mapView为BMKMapView对象
    
    //地理反编码
    
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    
    reverseGeocodeSearchOption.reverseGeoPoint = userLocation.location.coordinate;
    
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
    
    if(flag){
        
        NSLog(@"反geo检索发送成功");
        
        [_locService stopUserLocationService];
        
    }else{
        
        NSLog(@"反geo检索发送失败");
        
    }
    
}

#pragma mark -------------地理反编码的delegate---------------

-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error

{
    
    NSLog(@"address:%@----%@",result.addressDetail,result.address);
    
    //addressDetail:     层次化地址信息
    
    //address:    地址名称
    
    //businessCircle:  商圈名称
    
    // location:  地址坐标
    
    //  poiList:   地址周边POI信息，成员类型为BMKPoiInfo
    _label_address.text = result.address;
    _addressInfo.address = result.address;
}

//定位失败

- (void)didFailToLocateUserWithError:(NSError *)error{
    
    NSLog(@"error:%@",error);
    
}

@end
